<h1>Memory Blocks</h1>

<p>
Go is a language which supports automatic memory management,
such as automatic memory allocation and automatic garbage collection.
So Go programmers can do programming without handling the underlying verbose memory management.
This ont only brings much convenience and saves Go programmers lots of time,
but also helps Go programmers avoid many careless bugs.
</p>

<p>
Although knowing the underlying memory management implementation details is not necessary
for Go programmers to write Go code, understanding some concepts and being aware of some facts
in the memory management implementation by the standard Go compiler and runtime is very
helpful for Go programmers to write high quality Go code.
</p>

<p>
This article will explain some concepts and list some facts of the implementation of
memory block allocation and garbage collection by the standard Go compiler and runtime.
Other aspects, such as memory apply and memory release in memory management,
will not be touched in this article.
</p>

<a class="anchor" id="memory-block"></a>
<h3>Memory Blocks</h3>

<p>
A memory block is a continuous memory segment to host
<a href="value-part.html">value parts</a> at run time.
Different memory blocks may have different sizes, to host different value parts.
One memory block may host multiple value parts at the same time,
but each value part can only be hosted within one memory block,
no matter how large the size of that value part is.
In other words, for any value part, it never crosses memory blocks.
</p>

<div>
There are many reasons when one memory block may host multiple value parts. Some of them:
<ul>
<li>
	a struct value often have several fields. So when a memory block is allocated for
	a struct value, the memory block will also host (the direct parts of) these field values.
</li>
<li>
	an array values often have many elements. So when a memory block is allocated for
	a array value, the memory block will also host (the direct parts of) the array element values.
</li>
<li>
	the underlying element sequences of two slices may be hosted on the same memory block,
	the two element sequences even can overlap with each other.
</li>
</ul>
</div>

<h3>A Value References the Memory Blocks Which Host Its Value Parts</h3>

<p>
We have known that a value part can reference another value part.
Here, we extend the reference definition by saying
a memory block is referenced by all the value parts it hosts.
So if a value part <code>v</code> is referenced by another value part,
then the other value will also reference the memory block hosting <code>v</code>, indirectly.
</p>

<a class="anchor" id="when-to-allocate"></a>
<h3>When Will Memory Blocks Be Allocated?</h3>

<div>
In Go, memory blocks may be allocated but not limited at following situations:
<ul>
<li>
	explicitly call the <code>new</code> and <code>make</code> built-in functions.
	A <code>new</code> call will always allocate exact one memory block.
	A <code>make</code> call will allocate more than one memory blocks to host
	the direct part and underlying part(s) of the created slice, map or channel value.
</li>
<li>
	create maps, slices and anonymous functions with corresponding literals.
	More than one memory blocks may be allocated in each of the processes.
</li>
<li>
	declare variables.
</li>
<li>
	assign non-interface values to interface values
	(when the non-interface value is not a pointer value).
</li>
<li>
	concatenate non-constant strings.
</li>
<li>
	convert strings to byte or rune slices, and vice versa,
	except <a href="string.html#conversion-optimizations">some special compiler optimization cases</a>.
</li>
<li>
	convert integers to strings.
</li>
<li>
	call the built-in <code>append</code> function (when the capacity of the base slice is not large enough).
</li>
<li>
	add a new key-element entry pair into a map (when the underlying hash table needs to be resized).
</li>
</ul>

</div>

<a class="anchor" id="where-to-allocate"></a>
<h3>Where Will Memory Blocks Be Allocated On?</h3>

<p>
For every Go program compiled by the official standard Go compiler, at run time,
each goroutine will maintain a stack, which is a memory segment.
It acts as a memory pool for some memory blocks to be allocated from/on.
The initial stack size of each goroutine is small (about 2k bytes on 64-bit systems).
The stack size will grow and shrink as needed in goroutine running.
</p>

<p><i>
(Please note, for the standard Go compiler, there is a limit of stack size
each goroutine can have. For standard Go compiler 1.11, the default maximum stack size
is 1 GB on 64-bit systems, and 250 MB on 32-bit systems.
We can call the <code>SetMaxStack</code> function in the
<code>runtime/debug</code> standard package to change the size.)
</i></p>

<p>
Memory blocks can be allocated on stacks.
Memory blocks allocated on the stack of a goroutine can only be used (referenced)
in the goroutine internally.
They are goroutine localized resources.
They are not safe to be referenced crossing goroutines.
A goroutine can access or modify the value parts hosted on a memory block
allocated on the stack of the goroutine
without using any data synchronization techniques.
</p>

<p>
Heap is a singleton in each program. It is a virtual concept.
If a memory block is not allocated on any goroutine stack,
then we say the memory block is allocated on heap.
Value parts hosted on memory blocks allocated on heap
can be used by multiple goroutines.
In other words, they can be used concurrently.
Their uses should be synchronized when needed.
</p>

<p>
Heap is a conservative place to allocate memory blocks on.
If compilers detect a memory block will be referenced crossing goroutines
or can't easily confirm whether or not the memory block is safe to be put on the stack of a goroutine,
then the memory block will be allocated on heap at run time.
This means some values can be safely allocated on stacks may be also allocated on heap.
</p>

<!--
For the standard Go compiler,
https://docs.google.com/document/d/1CxgUBPlx9iJzkz9JWkb6tIpTe5q32QDmz8l0BouG0Cw/preview

very large memory blocks will always be allocated on heap?
https://github.com/golang/go/issues/20021

The values referenced by values allocated on heap will never be allocated in stacks.
-->

<div>
In fact, stacks are not essential for Go programs.
Go compiler/runtime can allocate all memory block on heap.
Supporting stacks is just to make Go programs run more efficiently:
<ul>
<li>
	allocating memory blocks on stacks is much faster than on heap.
</li>
<li>
	memory blocks allocated on a stack don't need to be garbage collected.
</li>
<li>
	stack memory blocks are more CPU cache friendly than heap ones.
</li>
</ul>
</div>

<p>
If a memory block is allocated somewhere, we can also say the value parts hosted
on the memory block are allocated on the same place.
</p>

<p>
If some value parts of a local variable declared in a function is allocated on heap,
we can say the value parts (and the variable) escape to heap.
By using the official Go SDK, we can run <code>go build -gcflags -m</code> to check
which local values (value parts) will escape to heap at run time.
As mentioned above, the current escape analyzer in the standard Go compiler
is still not perfect, many local value parts can be allocated on stacks safely
will still escape to heap.
</p>

<p>
An active value part allocated on heap still in use must be referenced by at least one value part allocated on a stack.
If a value escaping to heap is a declared local variable, and assume its type is <code>T</code>,
Go runtime will create (a memory block for)
an implicit pointer of type <code>*T</code> on the stack of the current goroutine.
The value of the pointer stores the address of the memory block allocated for the variable on heap
(a.k.a., the address of the local variable of type <code>T</code>).
Go compiler will also replace all uses of the variable with
the dereferences of the pointer value at compile time.
The <code>*T</code> pointer value on stack may be marked as dead since a later time,
so the reference relation from it to the <code>T</code> value on heap will disappear.
The reference relation from the <code>*T</code> value on stack to the <code>T</code> value on heap
plays an important role in the garbage collection process which will be described below.
</p>

<p>
Similarly, we can view each package-level variable is allocated on heap,
and the variable is referenced by an implicit pointer which is allocated on a global memory zone.
In fact, the implicit pointer references the direct part of the package-level variable,
and the direct part of the variable references some other value parts.
</p>

<p>
A memory block allocated on heap may be referenced by multiple value parts allocated on different stacks at the same time.
</p>

<div>
Some facts:
<ul>
<li>
	if a field of a struct value escapes to heap,
	then the whole struct value will also escape to heap.
</li>
<li>
	if an element of an array value escapes to heap,
	then the whole array value will also escape to heap.
</li>
<li>
	if an element of a slice value escapes to heap,
	then all the elements of the slice will also escape to heap.
</li>
<li>
	if a value (part) <code>v</code> is referenced by a value (part) which escapes to heap,
	then the value (part) <code>v</code> will also escape to heap.
</li>
</ul>
</div>

<p>
A memory block created by calling <code>new</code> function may be allocated on heap or stacks.
This is different to C++.
</p>

<p>
When the size of a goroutine stack changes, a new memory segment will be allocated for the stack.
So the memory blocks allocated on the stack will very likely be moved, or their addresses will change.
Consequently, the pointers, which must be also allocated on the stack,
referencing these memory blocks also need to be modified accordingly.
</p>

<!--p>
Another important fact we should know is,
to make 64-bit word atomic operations possible on 32-bit architectures,
the address of any memory block allocated on heap is guaranteed to be 8-byte aligned.
</p-->

<a class="anchor" id="when-can-collect"></a>
<h3>When Can a Memory Block Be Collected?</h3>

<p>
Memory blocks allocated for direct parts of package-level variables will never be collected.
</p>

<p>
The stack of a goroutine will be collected as a whole when the goroutine exits.
So there is no need to collect the memory blocks allocated on stacks, individually, one by one.
Stacks are not collected by the garbage collector.
</p>

<p>
For a memory block allocated on heap, it can be safely collected only if
it is no longer referenced (either directly or indirectly)
by all the value parts allocated on goroutine stacks and the global memory zone.
We call such memory blocks as unused memory blocks.
Unused memory blocks on heap will be collected by the garbage collector.
</p>

<div>
Here is an example to show when some memory blocks can be collected:
<pre class="line-numbers"><code class="language-go">package main

var p *int

func main() {
	done := make(chan bool)
	// "done" will be used in main and the following
	// new goroutine, so it will be allocated on heap.

	go func() {
		x, y, z := 123, 456, 789
		_ = z  // z can be allocated on stack safely.
		p = &x // For x and y are both ever referenced
		p = &y // by the global p, so they will be both
		       // allocated on heap.

		// Now, x is not referenced by anyone, so
		// its memory block can be collected now.

		p = nil
		// Now, y is als not referenced by anyone,
		// so its memory block can be collected now.

		done <- true
	}()

	<-done
	// Now the above goroutine exits, the done channel
	// is not used any more, a smart compiler may
	// think it can be collected now.

	// ...
}
</code></pre>

<p>
</p>

Sometimes, smart compilers, such as the standard Go compiler,
may make some optimizations so that some references
are removed earlier than we expect. Here is such an example.

<pre class="line-numbers"><code class="language-go">package main

import "fmt"

func main() {
	// Assume the length of the slice is so large
	// that its elements must be allocated on heap.
	bs := make([]byte, 1 << 31)

	// A smart compiler can detect that the
	// underlying part of the slice bs will never be
	// used later, so that the underlying part of the
	// slice bs can be garbage collected safely now.

	fmt.Println(len(bs))
}
</code></pre>

<p>
Please read <a href="value-part.html">value parts</a> to learn the
internal structures of slice values.
</p>

<p>
By the way, sometimes, we may hope the slice <code>bs</code> is guaranteed
to not being garbage collected until <code>fmt.Println</code> is called,
then we can use a <code>runtime.KeepAlive</code> function call to tell
garbage collectors that the slice <code>bs</code> and
the value parts referenced by it are still in use.
</p>

For example,

<pre class="line-numbers"><code class="language-go">package main

import "fmt"
import "runtime"

func main() {
	bs := make([]int, 1000000)

	fmt.Println(len(bs))

	// A runtime.KeepAlive(bs) call is also
	// okay for this specified example.
	runtime.KeepAlive(&bs)
}
</code></pre>

<p>
<code>runtime.KeepAlive</code> function calls are often needed
if <a href="unsafe.html">unsafe pointers</a> are involved.
</p>

</div>

<a class="anchor" id="how-to-detect"></a>
<h3>How Are Unused Memory Blocks Detected?</h3>

<div>
<p>
The current standard Go compiler (version 1.13) uses
a concurrent, tri-color, mark-sweep garbage collector.
Here this article will only make a simple explanation for the algorithm.
</p>

<p>
A garbage collection (GC) process is divided into two phases, the mark phase and the sweep phase.
In the mark phase, the collector (a group of goroutines actually) uses the tri-color algorithm to analyze
which memory blocks are unused.
</p>

The following quote is token from <a href="https://blog.golang.org/go15gc">a Go blog article</a>,
in which an <b><i>objects</i></b> is either value parts or memory blocks.

<blockquote style="margin-top:0px;margin-bottom:0px;">
<small>
	At the start of a GC cycle all objects are white.
	The GC visits all roots, which are objects directly accessible by the application
	such as globals and things on the stack, and colors these grey.
	The GC then chooses a grey object, blackens it, and then scans it for pointers to other objects.
	When this scan finds a pointer to a white object, it turns that object grey.
	This process repeats until there are no more grey objects.
	At this point, white objects are known to be unreachable and can be reused.
</small>
</blockquote>

<!--
<p>
There is a stop-the-world phase in garbage collecting. All goroutines must be paused in this phase.
After many improvements from version to version,
since v1.8, the collector makes typical worst-case stop-the-world duration less than 100μs (0.1 millisecond).
This generally removes noticeable lags at run time.
</p>
-->

<p>
About why the algorithm uses three colors instead of two colors, please search "write barrier golang" for details.
Here only provides two references: <a href="https://github.com/golang/proposal/blob/master/design/17503-eliminate-rescan.md">eliminate STW stack re-scanning</a> and <a href="https://golang.org/src/runtime/mbarrier.go">mbarrier.go</a>.
</p>

<p>
In the sweep phase, the marked unused memory blocks will be collected.
</p>

<p>
The GC algorithm is a non-compacting one, so it will not move memory blocks to rearrange them.
</p>
</div>

<a class="anchor" id="when-to-collect"></a>
<h3>When Will an Unused Memory Block Be Collected?</h3>

<div>

Unused heap memory blocks are viewed as garbage by Go runtime and will be collected to reuse or release memory.
The garbage collector is not always running. It will start when a threshold is satisfied.
So an unused memory block may be not collected immediately when it becomes unused.
Instead, it will be collected eventually.
Currently (Go 1.13), the threshold is controlled by
<a href="https://golang.org/pkg/runtime/#hdr-Environment_Variables">GOGC environment variable</a>:
<blockquote style="margin-top:0px;margin-bottom:0px;">
<small>
	The GOGC variable sets the initial garbage collection target percentage.
	A collection is triggered when the ratio of freshly allocated data to
	live data remaining after the previous collection reaches this percentage.
	The default is GOGC=100. Setting GOGC=off disables the garbage collector entirely.
</small>
</blockquote>

<p>
The value of this environment variable determines the frequency of garbage collecting,
and it can be modified at run time by calling
<a href="https://golang.org/pkg/runtime/debug/#SetGCPercent">runtime/debug.SetGCPercent</a> function.
Smaller values lead to more frequent garbage collections.
A negative percentage disables automatical garbage collection.
</p>

<p>
A garbage collection process can also be started manually by calling the
<a href="https://golang.org/pkg/runtime/#GC">runtime.GC</a> function.
</p>

<p>
An unused memory block may not be released to OS immediately after it is collected,
so that it can be reused for new some value parts.
Don't worry, the official Go runtime is much less memory greedy than most Java runtimes.
</p>
</div>
